package com.lihua.project.taskcenter.core.utils;

import com.lihua.common.utils.CacheUtils;
import com.lihua.project.taskcenter.taskcenter.domain.Task;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.cache.Cache;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author lihua
 * @date 2022/3/16 17:43
 * 对缓存中的任务列表的操作
 */
@Slf4j
public class TaskListUtils {

    private static final String TASK_CACHE = "taskCache";

    /**
     * 获取所有监督任务
     * */
    public static List<Task> getTaskAll(){
        return (List<Task>)CacheUtils.get(TASK_CACHE,"taskMatch");
    }

    /**
     * 根据id查询任务
     * @param id 任务id
     * @return 返回一个任务task，如果不存在，那么返回null
     * */
    public static Task selectTaskById(Long id){
        List<Task> tasks = (List<Task>)CacheUtils.get(TASK_CACHE, "taskMatch");
        Iterator<Task> iterator = tasks.iterator();
        while (iterator.hasNext()){
            Task task = iterator.next();
            if (task.getId().equals(id)){
               return task;
            }
        }
        return null;
    }

    /**
     * 插入一个监督任务到任务列表
     * */
    public static void addTask(Task task){
        try {
            List<Task> tasks = (List<Task>)CacheUtils.get(TASK_CACHE, "taskMatch");
            tasks.add(task);
            CacheUtils.put(TASK_CACHE,"taskMatch",tasks);
        }catch (RuntimeException e){
            log.warn("加入匹配队列异常 [exception message={}]",e.getMessage());
        }

    }

    /**
     * 根据任务id删除一个监督任务
     * */
    public static void deleteTasksByTasksId(Long taskId){
        List<Task> tasks = (List<Task>)CacheUtils.get(TASK_CACHE, "taskMatch");
        Iterator<Task> iterator = tasks.iterator();
        while (iterator.hasNext()){
            Task task = iterator.next();
            if (task.getId().equals(taskId)){
                iterator.remove();
                break;
            }
        }
    }
}
